package com.huluobo.kotlinim1907a.contract.login

import android.util.Log
import com.huluobo.kotlinim1907a.adapter.EMCallbackAdapter
import com.huluobo.kotlinim1907a.extention.isValidPassword
import com.huluobo.kotlinim1907a.extention.isValidUserName
import com.hyphenate.EMCallBack
import com.hyphenate.chat.EMClient
import com.hyphenate.chat.adapter.EMACallback

/**
 * Created by lc on 2022/1/12.
 */
class LoginPresenter(val view: LoginContract.View) : LoginContract.Presenter {
    override fun login(userName: String, password: String) {
        //1.验证用户名是否合法
        if (userName.isValidUserName()) {
            //2.验证密码是否合法
            if (password.isValidPassword()) {
                //3.开始出发登录进度条
                view.onStartLogin()
                //4.登录到环信,相当于M层
                loginEaseMob(userName, password)

            } else view.onPasswordError()
        } else view.onUserNameError()
    }

    private fun loginEaseMob(userName: String, password: String) {
        EMClient.getInstance().login(userName, password, object : EMCallbackAdapter() {
            override fun onSuccess() {
                EMClient.getInstance().groupManager().loadAllGroups()//读取所有的群组
                EMClient.getInstance().chatManager().loadAllConversations()//读取所有的会话列表
                //UI反馈登录成功,当前在子线程当中,需要更新主线程UI,会造成线程阻塞,所以需要切换到主线程UI
                runOnUIThread { view.onLoggedInSuccess() }
            }

            override fun onError(code: Int, error: String?) {
                Log.i("TagA", "onError:$code,error:$error")
                runOnUIThread { view.onLoggedInFailed() }
            }
        })
    }
}